<template>
  <view class="permission-apply-container">
    <!-- 未申请时显示表单 -->
    <view  class="apply-form">
      <view class="form-item">
        <text class="label">申请对象</text>
        <picker 
          @change="onAdminChange" 
          :range="adminList" 
          range-key="name"
          class="picker"
        >
          <view class="picker-text">
            {{ selectedAdmin ? selectedAdmin.name : '请选择审批人' }}
          </view>
        </picker>
      </view>

      <view class="form-item">
        <text class="label">申请权限</text>
        <picker 
          @change="onRoleChange" 
          :range="roleOptions" 
          range-key="label"
          class="picker"
        >
          <view class="picker-text">
            {{ selectedRole ? selectedRole.label : '请选择权限类型' }}
          </view>
        </picker>
      </view>

      <view class="form-item">
        <text class="label">申请理由</text>
        <textarea 
          v-model="applyReason" 
          placeholder="请详细说明申请理由..."
          class="textarea"
        />
      </view>

      <button 
        @click="submitApply" 
        type="primary" 
        :disabled="!canSubmit"
        class="submit-btn"
      >
        提交申请
      </button>
    </view>

    <!-- 已有申请时显示状态 -->
    <view  class="status-container">
      <view class="status-card">
        <text class="title">权限申请状态</text>
        
        <view class="info-item">
          <text class="info-label">申请对象：</text>
          <text class="info-value">{{ currentApplication.adminName }}</text>
        </view>

        <view class="info-item">
          <text class="info-label">申请权限：</text>
          <text class="info-value">{{ formatRole(currentApplication.role) }}</text>
        </view>

        <view class="info-item">
          <text class="info-label">申请时间：</text>
          <text class="info-value">{{ formatDate(currentApplication.createTime) }}</text>
        </view>

        <view class="status-display" :class="statusClass">
          {{ statusText }}
        </view>

        <view v-if="currentApplication.rejectReason" class="reject-reason">
          <text class="reason-label">拒绝理由：</text>
          <text class="reason-content">{{ currentApplication.rejectReason }}</text>
        </view>

        <button 
          v-if="canReapply" 
          @click="resetApply" 
          type="primary" 
          class="reapply-btn"
        >
          重新申请
        </button>
      </view>
    </view>
  </view>
</template>

<script>
	import { clearStorageAll,getUserInfo } from "../../../utils/auth.js"
export default {
  data() {
    return {
      adminList: [],        // 管理员列表
      selectedAdmin: {
		  name: '管理员'
	  },  // 选中的管理员
      roleOptions: [        // 权限选项
        { value: 'CREATOR', label: '内容创作者' },
        { value: 'ADMIN', label: '管理员' }
      ],
      selectedRole: null,   // 选中的权限
      applyReason: '',       // 申请理由
      currentApplication: {} // 当前申请信息
    }
  },
  computed: {
    // 是否可以提交
    canSubmit() {
      return this.selectedAdmin && this.selectedRole && this.applyReason.trim()
    },
    // 申请状态文本
    statusText() {
      const statusMap = {
        'PENDING': '审核中',
        'APPROVED': '已通过',
        'REJECTED': '已拒绝'
      }
      return statusMap[this.currentApplication.status] || '未知状态'
    },
    // 状态样式类
    statusClass() {
      return {
        'PENDING': 'status-pending',
        'APPROVED': 'status-approved',
        'REJECTED': 'status-rejected'
      }[this.currentApplication.status] || ''
    },
    // 是否可以重新申请
    canReapply() {
      return this.currentApplication.status === 'REJECTED'
    }
  },
  onLoad() {
    this.loadAdminList()
    this.checkApplication()
  },
  methods: {
    // 加载管理员列表
    async loadAdminList() {
      try {
        const res = await uni.$http.get('/user/admins')
        if (res.data.code === 200) {
          this.adminList = res.data.data
        }
      } catch (e) {
        console.error('加载管理员失败:', e)
      }
    },
    
    // 检查当前申请状态
    async checkApplication() {
      try {
        const res = await uni.$http.get('/application/current')
        if (res.data.code === 200 && res.data.data) {
          this.currentApplication = res.data.data
          this.hasApplication = true
        }
      } catch (e) {
        console.error('检查申请状态失败:', e)
      }
    },
    
    // 管理员选择变化
    onAdminChange(e) {
      this.selectedAdmin = this.adminList[e.detail.value]
    },
    
    // 权限选择变化
    onRoleChange(e) {
      this.selectedRole = this.roleOptions[e.detail.value]
    },
    
    // 提交申请
    async submitApply() {
		if(getUserInfo().role == 0) {
			uni.showToast({
				title: '不能降低权限',
				duration: 2000,
				icon: 'error'
			});
			return;
		}
		
      if (!this.canSubmit) return
      
      try {
        const params = {
          adminId: this.selectedAdmin.id,
          role: this.selectedRole.value,
          reason: this.applyReason
        }
        
        uni.showLoading({ title: '提交中...' })
        const res = await uni.$http.post('/application/apply', params)
        uni.hideLoading()
        
        if (res.data.code === 200) {
          uni.showToast({ title: '提交成功' })
          this.checkApplication() // 重新检查状态
        }
      } catch (e) {
        uni.hideLoading()
        uni.showToast({ title: '提交失败', icon: 'none' })
      }
    },
    
    // 重置申请（重新申请）
    resetApply() {
      this.hasApplication = false
      this.selectedAdmin = null
      this.selectedRole = null
      this.applyReason = ''
    },
    
    // 格式化权限显示
    formatRole(role) {
      const roleMap = {
        'CREATOR': '内容创作者',
        'ADMIN': '管理员'
      }
      return roleMap[role] || role
    },
    
    // 格式化日期显示
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
    }
  }
}
</script>

<style scoped>
.permission-apply-container {
  padding: 30rpx;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 表单样式 */
.apply-form {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.form-item {
  margin-bottom: 40rpx;
}

.label {
  display: block;
  font-size: 30rpx;
  color: #333;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.picker {
  background-color: #f8f8f8;
  border-radius: 12rpx;
  padding: 20rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.textarea {
  height: 200rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  width: 100%;
  box-sizing: border-box;
}

.submit-btn {
  margin-top: 60rpx;
  font-size: 32rpx;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
}

/* 状态显示样式 */
.status-container {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  margin-top: 20px;
}

.status-card {
  padding: 20rpx;
}

.title {
  font-size: 36rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 40rpx;
  display: block;
}

.info-item {
  display: flex;
  margin-bottom: 24rpx;
  font-size: 28rpx;
}

.info-label {
  color: #666;
  width: 160rpx;
}

.info-value {
  color: #333;
  flex: 1;
}

.status-display {
  margin: 40rpx auto;
  padding: 20rpx 0;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 12rpx;
  width: 80%;
}

.status-pending {
  background-color: #FFF3E0;
  color: #FF9800;
}

.status-approved {
  background-color: #E8F5E9;
  color: #4CAF50;
}

.status-rejected {
  background-color: #FFEBEE;
  color: #F44336;
}

.reject-reason {
  margin-top: 30rpx;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
}

.reason-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.reason-content {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

.reapply-btn {
  margin-top: 60rpx;
  font-size: 32rpx;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
}
</style>